package com.yix.admin.modules.security.service;

import com.yix.admin.modules.security.config.bean.LoginProperties;
import com.yix.admin.modules.security.dto.SecurityUserDetails;
import com.yix.admin.modules.system.entity.dto.SysUserDto;
import com.yix.admin.modules.system.service.DataService;
import com.yix.admin.modules.system.service.SysRoleService;
import com.yix.admin.modules.system.service.SysUserService;
import com.yix.common.exception.BadRequestException;
import com.yix.common.exception.EntityNotFoundException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author wdx
 * @version 1.0
 * @Description TODO
 * @date 2021/1/21 9:08
 */
@RequiredArgsConstructor
@Service("userDetailsService")
@Slf4j
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private LoginProperties loginProperties;
    @Autowired
    private DataService dataService;

    /**
     * 用户信息缓存
     *
     * @see {@link UserCacheClean}
     */
    static Map<String, SecurityUserDetails> userDtoCache = new ConcurrentHashMap<>();

    @Override
    public SecurityUserDetails loadUserByUsername(String username) {
        boolean searchDb = true;
        SecurityUserDetails jwtUserDto = null;
        if (loginProperties.isCacheEnable() && userDtoCache.containsKey(username)) {
            jwtUserDto = userDtoCache.get(username);
            searchDb = false;
        }
        if (searchDb) {
            SysUserDto user;
            try {
                user = sysUserService.findByName(username);
            } catch (EntityNotFoundException e) {
                // SpringSecurity会自动转换UsernameNotFoundException为BadCredentialsException
                throw new UsernameNotFoundException("", e);
            }
            if (user == null) {
                throw new UsernameNotFoundException("");
            } else {
                if (!user.getEnabled()) {
                    throw new BadRequestException("账号未激活！");
                }
                jwtUserDto = new SecurityUserDetails(
                        user,
                        dataService.getDeptIds(user),
                        sysRoleService.mapToGrantedAuthorities(user)
                );
                userDtoCache.put(username, jwtUserDto);
            }
        }
        return jwtUserDto;
    }
}
